package com.pxmeta.app.webhook.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pxmeta.common.constant.Status;
import com.pxmeta.common.core.domain.AjaxResult;
import com.pxmeta.common.enums.ContentAuditEnum;
import com.pxmeta.dynamic.entity.Dynamic;
import com.pxmeta.dynamic.service.IDynamicService;
import com.pxmeta.dynamic.service.IMailService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/audit")
@RequiredArgsConstructor
@Slf4j
public class AuditController {
    private final IDynamicService dynamicService;
    private final IMailService mailService;


    @PostMapping("/auditVideoHandler")
    public AjaxResult auditVideoHandler(@RequestParam("checksum") String checksum,
                                        @RequestParam("content") String content){
        JSONObject obj = JSONObject.parseObject(content);
        String dataId = obj.getString("dataId");
        long dynamicId = Long.parseLong(dataId);
        Dynamic dynamic = dynamicService.getById(dynamicId);
        JSONArray results = obj.getJSONArray("results");
        log.info("视频机器审核开始,动态id:{}",dynamicId);
        Status status = Status.SUCCESS;
        for (Object result : results) {
            String str = JSONObject.toJSONString(result);
            JSONObject jsonObject = JSONObject.parseObject(str);
            String suggestion = jsonObject.getString("suggestion");
            log.info("视频审核状态：{}",suggestion);
            if (ContentAuditEnum.BLOCK.getSuggestion().equals(suggestion)){
                //审核不通过
                status = Status.FAIL;
                break;
            }
            if (ContentAuditEnum.REVIEW.getSuggestion().equals(suggestion)){
                //需要人工审核
                status = Status.PENDING;
            }
        }
        if (Status.FAIL.getValue().equals(status.getValue())){
            dynamicService.removeById(dynamic);
        }else {
            dynamic.setStatus(status.getValue());
            dynamicService.updateById(dynamic);
        }


        if (status == Status.SUCCESS){
            mailService.sendNoticeMessage(dynamic.getUserId(),dynamic.getCircleId(),"您的动态审核通过！");
        }
        return AjaxResult.success();
    }



}
